<template>
  <view
    class="container"
    :style="{ paddingBottom: !pageDisabled ? '150rpx' : '0' }"
  >
    <view class="note-section" v-if="examineShow">
      <view style="display: flex">
        <up-button
          text="通过"
          type="primary"
          style="margin-right: 20rpx"
          @click="handlePass"
        />
        <up-button text="驳回" type="error" @click="handleReject" />
      </view>
      <up-textarea
        v-model="form.reject_message"
        placeholder="驳回时请填写审核说明"
        style="margin-top: 10rpx"
      ></up-textarea>
    </view>
    <view class="form-card">
      <up-form
        :model="form"
        :rules="rules"
        ref="formRef"
        labelPosition="left"
        labelWidth="160rpx"
      >
        <up-form-item
          :required="true"
          prop="borrow_code"
          label="领用单号"
          class="border-bottom"
        >
          <up-input
            v-model="form.borrow_code"
            placeholder="系统自动生成"
            readonly
            border="none"
            placeholder-class="codePlaceholder"
          ></up-input>
        </up-form-item>
        <up-form-item
          label="领用单名称"
          prop="borrow_name"
          class="border-bottom"
        >
          <up-input
            v-model="form.borrow_name"
            placeholder="请输入领用单名称"
            :readonly="pageDisabled"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="使用人"
          prop="user"
          class="border-bottom"
          @click="handleUserAdmin"
        >
          <view @click.self="handleUserAdmin">
            <up-input
              v-model="user.admin"
              placeholder="请选择使用人"
              border="none"
              :readonly="pageDisabled"
            ></up-input>
          </view>
          <template #right>
            <up-icon name="arrow-right"></up-icon>
          </template>
        </up-form-item>
        <up-form-item label="领用日期" prop="borrow_date" class="border-bottom">
          <uni-datetime-picker
            type="datetime"
            placeholder="请选择日期"
            clear-icon
            v-model="form.borrow_date"
            :border="false"
            :disabled="pageDisabled"
            :class="{ 'date-color': !form.borrow_date }"
            class="datetime-color"
          />
        </up-form-item>
        <up-form-item
          label="存放位置"
          prop="location"
          class="border-bottom"
          @click="handleLocation"
        >
          <view @click.self="handleLocation">
            <up-input
              v-model="location.name"
              placeholder="请选择存放位置"
              border="none"
              :readonly="pageDisabled"
            ></up-input>
          </view>
          <template #right>
            <up-icon name="arrow-right"></up-icon>
          </template>
        </up-form-item>
      </up-form>
    </view>
    <view class="note-section">
      <up-form-item label="备注" prop="remark" labelPosition="top">
        <up-textarea
          v-model="form.remark"
          placeholder="要留下点什么吗"
          style="margin-top: 10rpx"
          :disabled="pageDisabled"
        ></up-textarea>
      </up-form-item>
    </view>
    <view class="asset-list">
      <view class="list-header">
        <text>资产列表</text>
        <text class="count">共计: {{ assetDataList.length }}</text>
      </view>

      <view class="asset-item" v-for="item in assetDataList" :key="item.id">
        <!-- 左侧信息 -->
        <view class="asset-right-container">
          <up-image
            :src="getImage(item.image)"
            width="160rpx"
            height="160rpx"
          />
          <view class="status">
            <up-tag
              v-if="item.asset_state_name"
              :text="item.asset_state_name"
              size="mini"
            />
          </view>
        </view>
        <view class="asset-info">
          <view class="asset-name">{{ item.asset_name }}</view>
          <view class="info">使用部门：{{ item.department_name }}</view>
          <view class="info">资产管理员：{{ item.asset_admin_name }}</view>
          <view class="info">存放地点：{{ item.location_name }}</view>
          <view class="info">资产编码：{{ item.asset_code }}</view>
          <view class="info">RFID编码：{{ item.label_number }}</view>
        </view>
        <up-icon
          name="minus-circle"
          size="22"
          v-if="!pageDisabled"
          color="#f00"
          @click="handleDelete(item)"
        />
      </view>
    </view>

    <view class="footer-buttons" v-if="!pageDisabled">
      <up-button
        type="primary"
        :customStyle="{
          'margin-right': '20rpx',
        }"
        @click="handleAddList"
        >添加</up-button
      >
      <up-button type="primary" @click="handleSave">提交</up-button>
    </view>
  </view>

  <!-- 选人 -->
  <up-action-sheet
    :show="user.show"
    :actions="user.actions"
    title="请选择"
    @close="user.show = false"
    @select="userSelect"
  >
  </up-action-sheet>

  <!-- 选日期 -->
  <!-- <up-calendar
    :show="date.show"
    :mode="'single'"
    @confirm="onDateConfirm"
    @close="date.show = false"
  ></up-calendar> -->

  <up-datetime-picker
    v-model="date.model"
    :show="date.show"
    mode="date"
    @confirm="onDateConfirm"
    @cancel="date.show = false"
    :formatter="formatter"
  ></up-datetime-picker>

  <!-- 选存放位置 -->
  <up-action-sheet
    :show="location.show"
    :actions="location.actions"
    title="请选择"
    @close="location.show = false"
    @select="locationSelect"
  >
  </up-action-sheet>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { generateUUID, formatter, formatTimestamp } from "@/utils";
import http, { BASE_URL } from "@/api/request";
import { t } from "@/locale/index.js";

const formRef = ref(null);

const enumList = [
  { code: "getviewTable", name: "Sys_GetUserNameById" },
  { code: "getviewTable", name: "getAssetAddressList" },
];
const form = ref({
  borrow_code: "",
  borrow_name: "",
  user: "",
  borrow_date: "",
  location: "",
  remark: "",
});
const user = reactive({
  actions: [],
  admin: "",
  show: false,
});

const location = reactive({
  show: false,
  name: "",
  actions: [],
});

const date = reactive({
  show: false,
  model: Date.now(),
});

const assetDataList = ref([]);
const pageDisabled = ref(false);
const examineShow = ref(false);
const state = ref("");

onLoad(async (query) => {
  await getDataList();
  const data = uni.getStorageSync("assetInfoData");
  state.value = query.name;
  if (query.name === "add") {
    uni.setNavigationBarTitle({
      title: t("assetRequisition.add"),
    });
    examineShow.value = false;
    pageDisabled.value = false;
  } else if (query.name === "edit") {
    uni.setNavigationBarTitle({
      title: t("assetRequisition.edit"),
    });
    form.value = data;
    pageDisabled.value = false;
    await getAssetBorrowList();
  } else if (query.name === "detail") {
    uni.setNavigationBarTitle({
      title: t("assetRequisition.detail"),
    });
    form.value = data;
    pageDisabled.value = true;
    examineShow.value = false;
    await getAssetBorrowList();
  } else if (query.name === "examine") {
    uni.setNavigationBarTitle({
      title: t("assetRequisition.examine"),
    });
    form.value = data;
    pageDisabled.value = true;
    examineShow.value = true;
    await getAssetBorrowList();
  }

  user.admin = user.actions.find((item) => item.value === data?.user)?.name;
  location.name = location.actions.find(
    (item) => item.value === data?.location
  )?.name;
});

onUnload(() => {
  uni.removeStorageSync("assetInfoData");
});

const getAssetBorrowList = async () => {
  const params = [
    {
      id: generateUUID(),
      service: "Module",
      method: "getViewTable",
      param: {
        code: "getAssetBorrowDetByBorrowCode",
        filters: [{ name: "code", value: form.value.borrow_code }],
      },
    },
  ];

  const { code, isSuccess, result } = await http.post(
    "/api/module/GetBatchResult",
    params
  );
  if (code && isSuccess) {
    assetDataList.value = result[0].response.data.viewTable;
  }
};

onMounted(() => {
  uni.$on("assetSelected", handleAssetSelected);
});

onBeforeUnmount(() => {
  uni.$off("assetSelected", handleAssetSelected);
});

const handleAssetSelected = (data) => {
  data.forEach((item) => {
    const isDuplicate = assetDataList.value.some(
      (existingItem) => existingItem.id === item.id
    );
    if (!isDuplicate) {
      assetDataList.value.push(item);
    }
  });
};

const handlePass = async () => {
  uni.showLoading({
    title: "操作中...",
  });
  const data = {
    pageCode: "Assetrequisition",
    params: {
      args: [
        {
          name: "assetBorrowMstr",
          value: {
            approval_state: "APPROVED",
            id: form.value.id,
          },
        },
      ],
    },
    methodName: "updateStatus",
  };
  try {
    const { code, isSuccess } = await http.post("/api/module/Invoke", data);

    if (code && isSuccess) {
      uni.showToast({
        title: "通过",
        icon: "success",
      });
      uni.navigateBack();
    } else {
      uni.showToast({
        title: "失败",
        icon: "error",
      });
    }
  } catch {
    uni.showToast({
      title: "失败",
      icon: "error",
    });
  }
  uni.hideLoading();
};

const handleReject = async () => {
  uni.showLoading({
    title: "操作中...",
  });
  const data = {
    pageCode: "Assetrequisition",
    params: {
      args: [
        {
          name: "assetBorrowMstr",
          value: {
            approval_state: "REJECTED",
            reject_message: form.value.reject_message,
            id: form.value.id,
          },
        },
      ],
    },
    methodName: "updateStatus",
  };
  try {
    const { code, isSuccess } = await http.post("/api/module/Invoke", data);

    if (code && isSuccess) {
      uni.showToast({
        title: "驳回成功",
        icon: "success",
      });
      uni.navigateBack();
    } else {
      uni.showToast({
        title: "失败",
        icon: "error",
      });
    }
  } catch {
    uni.showToast({
      title: "失败",
      icon: "error",
    });
  }
  uni.hideLoading();
};

const hideKeyboard = () => {
  uni.hideKeyboard();
};

const handleAddList = () => {
  uni.navigateTo({
    url: "/components/assetsAddList/index",
  });
};

// 获取资产列表
const getDataList = async () => {
  const batchRequests = enumList.map((item) => {
    const params = [
      {
        id: generateUUID(),
        service: "Module",
        method: item.code,
        param: JSON.stringify({ code: item.name, filters: [] }),
      },
    ];

    return http.post("/api/module/GetBatchResult", params).then((res) => ({
      ...res,
      name: item.name,
    }));
  });

  try {
    const results = await Promise.all(batchRequests);

    results.forEach(({ name, result, isSuccess, code }) => {
      if (!isSuccess || !code) return;
      switch (name) {
        case "Sys_GetUserNameById":
          user.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.text,
              value: item.id,
            };
          });
          break;
        case "getAssetAddressList":
          location.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.asset_address_name,
              value: item.asset_address_code,
            };
          });
          break;
      }
    });
  } catch (error) {
    console.error("获取枚举失败:", error);
  }
};

const handleUserAdmin = () => {
  if (!pageDisabled.value) {
    user.show = true;
    hideKeyboard();
  }
};

const userSelect = (e) => {
  form.value.user = e.value;
  user.admin = e.name;
};

const handleDate = () => {
  if (!pageDisabled.value) {
    date.show = true;
    hideKeyboard();
  }
};

const onDateConfirm = (e) => {
  form.value.borrow_date = formatTimestamp(e.value, false);
  date.show = false;
};

const handleLocation = () => {
  if (!pageDisabled.value) {
    location.show = true;
    hideKeyboard();
  }
};

const locationSelect = (e) => {
  form.value.location = e.value;
  location.name = e.name;
};

const getImage = (image) => {
  const type = getItemType(image);
  if (image) {
    if (type === "ID") {
      return `${BASE_URL}/File/GetImage?fileId=${image}`;
    } else {
      return image;
    }
  }
  return "";
};

const getItemType = (item) => {
  const idPattern = /^[a-zA-Z0-9-]+$/; // 包含字母、数字和 - 符号
  const apiPattern = /^\/File\//; // 假设接口地址以 '/File/' 开头
  const pathPattern = /^\/(?!File)/; // 普通路径以 '/' 开头，但不以 '/File/' 开头
  const relativePathPattern = /^[^/]/; // 假设相对路径不以 '/' 开头

  if (idPattern.test(item)) {
    return "ID";
  } else if (apiPattern.test(item)) {
    return "接口"; // 识别接口地址
  } else if (pathPattern.test(item)) {
    return "路径"; // 识别普通路径
  } else if (relativePathPattern.test(item)) {
    return "相对路径"; // 识别相对路径
  } else {
    return "其他";
  }
};

const handleDelete = (item) => {
  assetDataList.value = assetDataList.value.filter(
    (items) => item.id !== items.id
  );
};

const handleSave = async () => {
  uni.showLoading({
    title: "提交中...",
  });
  if (state.value === "add" && form.value.id) {
    delete form.value.id;
  }

  const data = {
    pageCode: "Assetrequisition",
    params: {
      args: [
        {
          name: "assetBorrowMstr",
          value: form.value,
        },
        {
          name: "assetBorrowDets",
          value: assetDataList.value,
        },
      ],
    },
    methodName: "saveOrUpdate",
  };

  try {
    const { code, isSuccess } = await http.post("/api/module/Invoke", data);

    if (code && isSuccess) {
      uni.showToast({
        title: "提交成功",
        icon: "success",
      });

      if (state.value === "add") {
        formRef.value?.resetFields(); // 重置校验状态
        form.value = {
          borrow_code: "",
          borrow_name: "",
          user: "",
          borrow_date: "",
          location: "",
          remark: "",
        };
        assetDataList.value = [];
        user.admin = "";
        location.name = "";
      }
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: "提交失败",
        icon: "error",
      });
    }
  } catch {
    uni.showToast({
      title: "提交失败",
      icon: "error",
    });
  }
  uni.hideLoading();
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  padding-bottom: 150rpx;
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;

  .disabled {
    color: #ccc;
  }
}

.note-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.asset-list {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;

  .list-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
  }

  .asset-item:last-child {
    padding-bottom: 0;
  }

  .asset-item {
    display: flex;
    // align-items: center;
    justify-content: space-between;
    border-top: 1px solid #eee;
    padding: 20rpx 0;
    .asset-right-container {
      position: relative;
      .status {
        position: absolute;
        right: 0;
        top: 0;
      }
    }
    // .status {
    //   background-color: #4caf50;
    //   color: #fff;
    //   padding: 4rpx 12rpx;
    //   border-radius: 8rpx;
    //   font-size: 22rpx;
    // }

    .asset-info {
      flex: 1;
      padding-left: 20rpx;

      .asset-name {
        font-weight: bold;
        font-size: 28rpx;
        margin-bottom: 6rpx;
      }

      .info {
        color: #666;
        font-size: 24rpx;
      }
    }
  }
}

.footer-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
}
.border-bottom {
  border-bottom: 1px solid #f5f5f5;
}
.codePlaceholder {
  color: #000 !important;
}
:deep(.datetime-color .uni-date__x-input) {
  color: #000 !important;
  opacity: 1 !important;
}
:deep(.date-color .uni-date__x-input) {
  color: #C2C7CE !important;
  opacity: 1 !important;
}
:deep(.uni-date-editor--x__disabled) {
  opacity: 1 !important;
}
</style>
